import {Component, OnInit} from '@angular/core';
import {Http} from '@angular/http';
import {Router} from '@angular/router';

@Component({
  selector: 'app-book-list',
  templateUrl: './book-list.component.html',
  styleUrls: ['./book-list.component.css']
})
export class BookListComponent implements OnInit {

  types: Object = {};
  bookList: Array<Object>;

  pager = {
    number: 0,
    size: 10,
    first: true,
    last: false,
    totalPages: 0,
    items: [],
  };

  pre() {
    if (!this.pager.first) {
      this.pager.number--;
      this.getList()
    }
  }

  next() {
    if (!this.pager.last) {
      this.pager.number++;
      this.getList()
    }
  }

  goTo(n) {
    this.pager.number = n;
    this.getList()
  }

  setPager(pager) {
    this.pager.number = pager.number;
    this.pager.size = pager.size;
    this.pager.first = pager.first;
    this.pager.last = pager.last;
    this.pager.totalPages = pager.totalPages;
    this.pager.items = Array.from({length: pager.totalPages}, (v, i) => i)
  }

  getList() {
    this.http.post('book/list', null, {
      params: {
        page: this.pager.number,
        size: this.pager.size
      }
    }).map(res => res.json())
      .subscribe(data => {
        if (data.code === 0) {
          this.bookList = data.data.content
          this.setPager(data.data);
        }
      })
  }

  getTypeList() {
    return new Promise((resolve, reject) => {
      this.http.post('booktype/getBookTypeList', null)
        .map(response => response.json())
        .subscribe(data => {
          if (data.code === 0) {
            data.data.content.map(v => {
              this.types[v.id] = v.typeName
            });
            resolve()
          } else {
            reject(data.msg)
          }
        })
    })
  }

  setState(obj, state) {
    this.http.post('book/update', null, {
      params: {
        id: obj.id,
        state: state
      }
    }).map(res => res.json())
      .subscribe(data => {
        if (data.code === 0) {
          obj.state = data.data.state
        } else {
          alert(data.msg)
        }
      })
  }

  add() {
    this.router.navigate(['book-edit', 'add'])
  }

  edit(id) {
    this.router.navigate(['book-edit', id])
  }

  constructor(private http: Http, private router: Router) {
  }

  ngOnInit() {
    this.getTypeList().then(() => {
      this.getList()
    }).catch((err) => {
      alert(err)
    });
  }

}
